package com.yuanxiao.wechat.live.util;

import cn.hutool.json.JSONUtil;
import com.yuanxiao.common.core.result.R;
import com.yuanxiao.wechat.live.controller.feign.WechatFeignClient;
import com.yuanxiao.wechat.live.entity.GoodsInfo;
import com.yuanxiao.wechat.live.entity.WechatGoodsEntity;
import com.yuanxiao.wechat.live.entity.WechatLiveConfigEntity;
import com.yuanxiao.wechat.live.entity.WechatRoleConfigEntity;
import com.yuanxiao.wechat.live.feign.ThirdServerFeignClient;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.TimeUnit;

@Component
public class WechatUtil {
    private static final String TOKEN_KEY = "wechat_token";
    private static final String CLIENT_ID = "mall-weapp";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ThirdServerFeignClient thirdServerFeignClient;

    @Qualifier("wechatFeignClient")
    @Autowired
    private WechatFeignClient wechatFeignClient;

    public R getToken() {
        R tokenR = thirdServerFeignClient.getToken(CLIENT_ID);
        if (!"0".equals(tokenR.getCode())) {
            return tokenR;
        }
        return R.returnDataWrapper(tokenR.getData().toString());
    }

//    public R getToken() {
//        String accessToken = stringRedisTemplate.opsForValue().get(TOKEN_KEY);
//        if (StringUtils.isNotBlank(accessToken)) {
//            return R.returnDataWrapper(accessToken);
//        }
//
//        R wechatR = wechatRHandle(wechatFeignClient.getToken("client_credential", APPID, SECRET));
//
//        if (!"0".equals(wechatR.getCode())) {
//            return wechatR;
//        }
//        accessToken = (String) wechatR.get("access_token");
//        System.out.println(accessToken);
//        stringRedisTemplate.opsForValue().set(TOKEN_KEY, accessToken, (Integer) wechatR.get("expires_in"), TimeUnit.SECONDS);
//        return R.returnDataWrapper(accessToken);
//    }

    //-----------------------------商品管理-----------------------------------
    public R getLiveInfo(WechatLiveConfigEntity wechatLiveConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.getLiveInfo(wechatLiveConfigEntity,accessToken));
    }

    public R deleteGoodsInfo(WechatGoodsEntity wechatGoodsEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.deleteGoodsInfo(wechatGoodsEntity,accessToken));
    }
    public R resubmitGoodsAudit(WechatGoodsEntity wechatGoodsEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.resubmitGoodsAudit(wechatGoodsEntity,accessToken));
    }

    public R getGoodsAuditInfo(WechatGoodsEntity wechatGoodsEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.getGoodsAuditInfo(wechatGoodsEntity,accessToken));
    }
    public R addGoods(WechatGoodsEntity wechatGoodsEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        GoodsInfo goodsInfo = new GoodsInfo();
        goodsInfo.setGoodsInfo(wechatGoodsEntity);
        return wechatRHandle(wechatFeignClient.addGoods(goodsInfo,accessToken));
    }

    public R resetGoodsAudit(WechatGoodsEntity wechatGoodsEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.resetGoodsAudit(wechatGoodsEntity,accessToken));
    }
    //-----------------------------人员管理-----------------------------------
    public R getRoleList(WechatRoleConfigEntity wechatRoleConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.getRoleList(wechatRoleConfigEntity.getRole(),
                wechatRoleConfigEntity.getKeyword(),accessToken));
    }
    public R addRole(WechatRoleConfigEntity wechatRoleConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.addRole(wechatRoleConfigEntity,accessToken));
    }
    public R deleteRole(WechatRoleConfigEntity wechatRoleConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.deleteRole(wechatRoleConfigEntity,accessToken));
    }

    //----------------------------直播间------------------------------------
    public R getPushUrl(WechatLiveConfigEntity wechatLiveConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.getPushUrl(wechatLiveConfigEntity.getRoomId(), accessToken));
    }
    public R downloadGoodsVideo(WechatLiveConfigEntity wechatLiveConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.downloadGoodsVideo(wechatLiveConfigEntity, accessToken));
    }

    public R getAssistantList(WechatLiveConfigEntity wechatLiveConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.getAssistantList(wechatLiveConfigEntity.getRoomId(), accessToken));
    }
    public R modifyAssistant(WechatLiveConfigEntity wechatLiveConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.modifyAssistant(wechatLiveConfigEntity, accessToken));
    }
    public R removeAssistant(WechatLiveConfigEntity wechatLiveConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.removeAssistant(wechatLiveConfigEntity, accessToken));
    }
    public R addAssistant(WechatLiveConfigEntity wechatLiveConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.addAssistant(wechatLiveConfigEntity, accessToken));
    }
    public R pushGoods(WechatLiveConfigEntity wechatLiveConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.pushGoods(wechatLiveConfigEntity, accessToken));
    }

    public R getShareCode(WechatLiveConfigEntity wechatLiveConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.getSharedCode(wechatLiveConfigEntity.getRoomId(), accessToken));
    }

    public R deleteGoods(WechatLiveConfigEntity wechatLiveConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.deleteGoods(wechatLiveConfigEntity,accessToken));
    }
    public R saleGoods(WechatLiveConfigEntity wechatLiveConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.saleGoods(wechatLiveConfigEntity,accessToken));
    }
    public R importGoods(WechatLiveConfigEntity wechatLiveConfigEntity){
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.importGoods(wechatLiveConfigEntity,accessToken));
    }
    public R deleteRoom(WechatLiveConfigEntity wechatLiveConfigEntity) {
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        return wechatRHandle(wechatFeignClient.deleteRoom(wechatLiveConfigEntity,accessToken));
    }

    public R editRoom(WechatLiveConfigEntity wechatLiveConfigEntity) {
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();

        return wechatRHandle(wechatFeignClient.editRoom(wechatLiveConfigEntity, accessToken));
    }

    public R createRoom(WechatLiveConfigEntity wechatLiveConfigEntity) {
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();

        return wechatRHandle(wechatFeignClient.createRoom(wechatLiveConfigEntity, accessToken));
    }
    public R getTempMedia(String mediaId) {
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();
        ResponseEntity<byte[]> tempMedia = wechatFeignClient.getTempMedia(mediaId, accessToken);

        byte[] img = tempMedia.getBody();

        return R.returnDataWrapper((Object) img);
    }
    public R uploadTempImg(MultipartFile file) throws IOException {
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();

        //临时图片地址
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + accessToken + "&type=image";

        return R.returnDataWrapper(uploadByFormDataType(file, url));
    }


    public Object uploadByFormDataType(MultipartFile file, String url) throws IOException {
        // 设置请求头，包含form-data格式
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        File tempFile = new File(file.getOriginalFilename() != null ? file.getOriginalFilename() : "tempImg");

        FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);

        // 设置请求体，将文件内容包装为form-data格式
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", new FileSystemResource(tempFile));

        // 创建请求实体对象
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 发送POST请求，将文件传递给另一个微服务
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        tempFile.delete();

        return JSONUtil.toBean(response.getBody(), Object.class);
    }

    public R uploadTempImgUrl(String imageUrl) throws IOException {
        R r = getToken();
        if (!"0".equals(r.getCode())) {
            return r;
        }
        String accessToken = (String) r.getData();

        // 临时图片地址
        String url = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + accessToken + "&type=image";

        return R.returnDataWrapper(uploadByFormDataTypeUrl(imageUrl, url));
    }

    public Object uploadByFormDataTypeUrl(String imageUrl, String url) throws IOException {
        // 设置请求头，包含form-data格式
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 创建请求体，将图片 URL 转换成文件流并包装为form-data格式
        URL imageURL = new URL(imageUrl);

        URLConnection connection = imageURL.openConnection();
        String contentType = connection.getContentType();

        InputStream imageStream = imageURL.openStream();
        File tempFile = new File("tempImg" + getWindowsFileExtension(contentType));
        FileUtils.copyInputStreamToFile(imageStream, tempFile);

        // 缩放图片至最大宽度或最大高度为300px
        BufferedImage image = ImageIO.read(tempFile);
        int maxWidth = 300;
        int maxHeight = 300;
        if (image.getWidth() > maxWidth || image.getHeight() > maxHeight) {
            int newWidth = Math.min(image.getWidth(), maxWidth);
            int newHeight = Math.min(image.getHeight(), maxHeight);

            Image scaledImage = image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
            BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D graphics = resizedImage.createGraphics();
            graphics.drawImage(scaledImage, 0, 0, null);
            graphics.dispose();

            ImageIO.write(resizedImage, "jpg", tempFile);
        }

        // 设置请求体，将文件内容包装为form-data格式
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", new FileSystemResource(tempFile));

        // 创建请求实体对象
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 发送POST请求，将文件传递给另一个微服务
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        tempFile.delete();

        return JSONUtil.toBean(response.getBody(), Object.class);
    }
    public static String getWindowsFileExtension(String mimeType) {
        switch (mimeType) {
            case "image/png":
                return ".png";
            case "image/jpeg":
                return ".jpg";
            case "image/jpg":
                return ".jpg";
            case "image/gif":
                return ".gif";
            default:
                return ""; // 未知类型，返回空字符串或其他默认值
        }
    }

    public R wechatRHandle(R wechatR) {
        Object wechatCode = wechatR.get("errcode");
        Object wechatErrMsg = wechatR.get("errmsg");
        Object wechatMsg = wechatR.get("msg");
        if (wechatCode != null) {
            wechatR.put("code", wechatCode.toString());
        }else return wechatR;
        if (wechatErrMsg != null) {
            wechatR.put("message", wechatErrMsg.toString());
        }
        if (wechatMsg != null) {
            wechatR.put("message", wechatMsg.toString());
        }

        //主播间配置错误返回集合
        if ("200002".equals(wechatCode.toString())) {
            wechatR.put("message", "入参错误");
        }

        if ("300022".equals(wechatCode.toString())) {
            wechatR.put("message", "此房间号不存在");
        }

        if ("300023".equals(wechatCode.toString())) {
            wechatR.put("message", "直播间当前状态不支持此操作");
        }

        if ("300024".equals(wechatCode.toString())) {
            wechatR.put("message", "商品不存在");
        }

        if ("300025".equals(wechatCode.toString())) {
            wechatR.put("message", "商品审核未通过");
        }

        if ("300027".equals(wechatCode.toString())) {
            wechatR.put("message", "导入商品失败");
        }

        if ("300033".equals(wechatCode.toString())) {
            wechatR.put("message", "添加商品超过直播间上限");
        }

        if ("300044".equals(wechatCode.toString())) {
            wechatR.put("message", "商品没有讲解视频");
        }

        if ("300045".equals(wechatCode.toString())) {
            wechatR.put("message", "讲解视频未生成");
        }

        if ("300047".equals(wechatCode.toString())) {
            wechatR.put("message", "已有商品正在推送，请稍后再试");
        }

        if ("300052".equals(wechatCode.toString())) {
            wechatR.put("message", "已下架的商品无法推送");
        }

        if ("300053".equals(wechatCode.toString())) {
            wechatR.put("message", "直播间未添加此商品");
        }

        //角色配置错误返回集合
        if ("400001".equals(wechatCode.toString())) {
            wechatR.put("message", "微信号不合规");
        }
        if ("400002".equals(wechatCode.toString())) {
            wechatR.put("message", "主播角色微信号需认证，请扫描二维码认证");
        }
        if ("400003".equals(wechatCode.toString())) {
            wechatR.put("message", "添加角色达到上限（管理员10个，运营者500个，主播500个）");
        }
        if ("400004".equals(wechatCode.toString())) {
            wechatR.put("message", "角色设置重复");
        }
        if ("400005".equals(wechatCode.toString())) {
            wechatR.put("message", "主播角色删除失败，该主播存在未开播的直播间");
        }
        //商品配置错误返回集合
        if ("300002".equals(wechatCode.toString())) {
            wechatR.put("message", "名称长度不符合规则");
        }
        if ("300003".equals(wechatCode.toString())) {
            wechatR.put("message", "价格输入不合规（如现价比原价大、传入价格非数字等）");
        }
        if ("300004".equals(wechatCode.toString())) {
            wechatR.put("message", "商品名称存在违规违法内容");
        }
        if ("300006".equals(wechatCode.toString())) {
            wechatR.put("message", "图片上传失败（如：mediaID过期）");
        }
        if ("300007".equals(wechatCode.toString())) {
            wechatR.put("message", "线上小程序版本不存在该链接");
        }
        if ("300009".equals(wechatCode.toString())) {
            wechatR.put("message", "商品审核撤回失败");
        }
        if ("300010".equals(wechatCode.toString())) {
            wechatR.put("message", "当前审核状态下不可撤回");
        }
        if ("300011".equals(wechatCode.toString())) {
            wechatR.put("message", "操作非法（API不允许操作非API创建的商品）");
        }
        if ("300017".equals(wechatCode.toString())) {
            wechatR.put("message", "商品未提审");
        }
        if ("300018".equals(wechatCode.toString())) {
            wechatR.put("message", "商品图片尺寸过大");
        }
        if ("300021".equals(wechatCode.toString())) {
            wechatR.put("message", "商品添加成功，审核失败");
        }
        return wechatR;
    }
}
